
import json

# 报文类作为 应用 -- 转发服务器 -- 接口 之间的单元
# 报文类内部分为两部分
# * 基本信息, baseInfo
# * 命令信息, cmdInfo
# 上述两部分的格式是接近的, 且在发送接收时, 也基本相同, 基本格式如下
# { "attribute": {}, "value": []}
# 最终汇总为
# {
#   "cmdInfo": { "attribute": {}, "value": []},
#   "baseInfo": { "attribute": {}, "value": []}
# }
class Msg:
    def __init__(self, deviceId, cmdString, tag=None) -> None:
        self.obj = {
            "deviceId": deviceId,
            "cmd": cmdString,
            "tag": tag,
            "cmdInfo": {
                "attribute": {},
                "value": []
            },
            "baseInfo": {
                "attribute": {},
                "value":[]
            }
        }

    def jsonFormatCheck(jsonString):
        try:
            msgInfo = json.loads(jsonString.decode("utf8"))
        except Exception:
            return False, "is not json format"
                        
        if msgInfo.get("deviceId") is None:
            return False, "can't find device Id"
        
        if msgInfo.get("cmd") is None:
            return False, "can't find cmd"
            
        return True, ""
    
    
    def addKeyValue(self, name, value):
        self.obj[name] = value

    def update(self, dictObj):
        self.obj.update(dictObj)

    def object(self):
        return self.obj
    
    def setCmdValue(self, value):
        self.obj["cmdInfo"]["value"] = value
    def setBaseValue(self, value):
        self.obj["baseInfo"]["value"] = value
    
    def complete(self, profile, cmdDirection, completeValue=True):
        # 补全 attribute
        self.obj["baseInfo"]["attribute"] = profile["baseInfo"]
        for cmd in profile["cmdList"][cmdDirection]:
            if cmd["cmd"] == self.obj["cmd"] and (self.obj["tag"] == None or self.obj["tag"] == cmd["tag"]):
                self.obj["cmdInfo"]["attribute"] = cmd
                break
        else:
            return False, "can't match cmd %s" % self.obj["cmd"]
        
        # 补全value
        if completeValue == True:
            for i in range(len(self.obj["baseInfo"]["attribute"])):
                if len(self.obj["baseInfo"]["value"]) < (i + 1):
                    if self.obj["baseInfo"]["attribute"][i].get("combo") is not None:
                        defaultIndex = self.obj["baseInfo"]["attribute"][i]["default"]
                        self.obj["baseInfo"]["value"].append(self.obj["baseInfo"]["attribute"][i]["combo"][defaultIndex][1])
                    else:
                        self.obj["baseInfo"]["value"].append(self.obj["baseInfo"]["attribute"][i]["default"])

            
            for i in range(len(self.obj["cmdInfo"]["attribute"]["parameter"])):
                parameter = self.obj["cmdInfo"]["attribute"]["parameter"][i]

                if len(self.obj["cmdInfo"]["value"]) < (i + 1):
                    if parameter.get("combo") is not None:
                        defaultIndex = parameter["default"]
                        self.obj["cmdInfo"]["value"].append(parameter["combo"][defaultIndex][1])
                    else:
                        self.obj["cmdInfo"]["value"].append(parameter["default"])
        
        return True, ""

    # json输出
    def jsonString(self):

        return json.dumps(self.obj, ensure_ascii=False)